package com.link.base.wechat.authweb.controller;

import com.link.core.cllog.LCLogger;
import com.link.base.wechat.authweb.model.AuthWeb;
import com.link.base.wechat.authweb.service.AuthWebService;
import com.link.base.wechat.basic.util.WxCommonUtil;
import com.link.base.wechat.thirdparty.service.ThirdPartyAuthService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.base.core.basic.util.YmlConstants;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信网页授权
 *
 * @author ouyangzhenqiang
 * @date 2019/03/10 23:39
 */
@Controller
@RequestMapping("/link/wxAuthWeb")
public class AuthWebController {
    @Resource
    private AuthWebService authWebService;
    @Resource
    private ThirdPartyAuthService thirdPartyAuthService;

    /**
     * 接收url，通过服务端重定向微信授权链接获取code、openId，并将openId拼接到url，执行重定向操作
     *
     * @author ouyangzhenqiang
     * @date 2019/03/11 10:45
     */
    @RequestMapping(value = {"/redirect"}, method = RequestMethod.GET)
    public void redirect(HttpSession session,
                              HttpServletRequest request, HttpServletResponse response) throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            // 真正需要打开的链接
            String redirectUrl = request.getParameter("url");
            if (StringUtils.isBlank(redirectUrl)) {
                throw new ServiceException("AUTHWEB-001");
            }
            // 微信公众号应用Id
            String wxAppId = request.getParameter("wxAppId");
            if (StringUtils.isBlank(wxAppId)) {
                throw new ServiceException("AUTHWEB-002");
            }
            // 网页授权scope => base/user
            String scope = WxCommonUtil.nullToString(request.getParameter("scope"));
            // 授权模式 => id/code
            String authType = WxCommonUtil.nullToString(request.getParameter("auth_type"));

            // 缓存核心信息
            String crmRedisKey = thirdPartyAuthService.createCrmToken();
            j.hset(crmRedisKey, "wxAppId", wxAppId);
            j.hset(crmRedisKey, "redirectUrl", redirectUrl);
            j.hset(crmRedisKey, "auth_type", authType);
            // 获取授权链接并重定向
            String authWebUrl = authWebService.generateAuthWebUrl(wxAppId, scope, crmRedisKey);
            response.sendRedirect(authWebUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
            response.sendRedirect(YmlConstants.getWxComponentAuthRedirectUrl() + "/weixinauthwebfail.html");
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    /**
     * 接收code并处理相关事项，最终重定向到真正需要打开的url（带上openId）
     *
     * @author ouyangzhenqiang
     * @date 2019/03/11 01:47
     */
    @RequestMapping(value = {"/receiveCode"}, method = RequestMethod.GET)
    public void receiveDevCode(HttpSession session,
                                                  HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        String crmRedisKey = request.getParameter("state");
        String redirectUrl = "";
        try {
            redirectUrl = authWebService.dealCodeReturnRedirectUrl(code, crmRedisKey);
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            LCLogger.withException(e);
            response.sendRedirect(YmlConstants.getWxComponentAuthRedirectUrl() + "/weixinauthwebfail.html");
        }
    }

    /**
     * 根据code和微信公众号应用Id获取用户信息
     *
     * @author ouyangzhenqiang
     * @date 2019/03/11 01:47
     */
    @RequestMapping(value = {"/getUserByCode"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getUserByCode(HttpSession session,
                               HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String code = request.getParameter("code");
            String wxAppId = request.getParameter("wxAppId");
            if (StringUtils.isBlank(code) || StringUtils.isBlank(wxAppId)) {
                throw new ServiceException("AUTHWEB-003");
            }
            AuthWeb authWeb = authWebService.getUserByCode(code, wxAppId);
            authWeb.setRefresh_token("");
            result.put("result", authWeb);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
